package com.demo.function.dataauth.aop;

import com.demo.function.dataauth.annotation.DataAuth;
import com.demo.function.dataauth.config.DataAuthProperty;
import com.demo.function.dataauth.manager.DataAuthManager;
import com.demo.starter.aop.AopUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @DataAuth拦截器
 */
@Slf4j
@Aspect
@Configuration
public class DataAuthAop {

    @Resource
    private DataAuthProperty dataAuthProperty;

    @Pointcut("@annotation(com.demo.function.dataauth.annotation.DataAuth)")
    public void addAdvice() {}

    @Around("addAdvice()")
    public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
        Method method = AopUtil.getMethod(pjp);
        DataAuth dataAuth = method.getAnnotation(DataAuth.class);

        try (DataAuthManager instance = DataAuthManager.create()) {
            instance.setHeaderKey(dataAuthProperty.getHeaderKey());
            instance.setTableName(dataAuth.tableName());
            instance.setColumnName(dataAuth.columnName());

            return pjp.proceed();
        }
    }
}
